package com.event.example.mybatis.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.event.cacheclear.service.IBatchClearCacheService;
import com.event.common.annotation.RepoSwitch;
import com.event.common.face.IClearNameSpace;
import com.event.example.constant.CacheKey;
import com.event.example.constant.CacheNameSpace;
import com.event.example.mybatis.Tag;
import com.event.example.mybatis.TagMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TagService extends ServiceImpl<TagMapper, Tag> implements IClearNameSpace<Tag> {
    @Resource
    private TagMapper tagMapper;

    @Autowired
    private IBatchClearCacheService batchClearCacheService;

    @RepoSwitch(value = false)
    public void insertList(List<Tag> tags){
        batchClearCacheService.batchClearInsertCache(CacheNameSpace.TOP_ORDER_MAPPER, ()->{
            saveBatch(tags);
            return tags.stream().map(Tag::getTagId).collect(Collectors.toList());
        });
    }

    public void updateList(List<Tag> tags){
        this.updateBatchById(tags);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(Tag tag){
        return tagMapper.updateById(tag) > 0;
    }

    public boolean deleteById(Integer id){
        return tagMapper.deleteById(id) > 0;
    }

    @Cacheable(cacheNames = CacheKey.CACHEMANAGER_ONE_MINUTE, key =  CacheNameSpace.ORDER_INDEX_USERSTAT,sync = true)
    public Tag selectById(Integer id){
        return tagMapper.selectById(id);
    }

    public void insert(Tag tag){
        tagMapper.insert(tag);
    }

    @Override
    public String namespaceAlias() {
        return CacheNameSpace.TOP_ORDER_MAPPER;
    }

    @Override
    public List<Tag> getRecordByIds(List<? extends Serializable> ids) {
        return tagMapper.selectBatchIds(ids);
    }

    @Override
    public Function<Tag, Object>[] idValues() {
        Function<Tag, Object> idValue = Tag::getTagId;
        Function<Tag, Object>[] result = new Function[]{idValue};
        return result;
    }
}
